import { useUserStore } from '@/store/user'

/**
 * 创建流式连接
 * @param {string} url 请求地址
 * @param {object} data 发送数据
 * @param {function} onMessage 消息回调
 * @param {function} onError 错误回调
 */

export const createStreamConnection = async (url, data, { onMessage, onError }) => {
  const userStore = useUserStore()
  const token = userStore.token

  console.info(`[Stream] 初始化连接：URL=${url}，Token=${token}`)

  let reconnectAttempts = 0
  const maxReconnectAttempts = 5
  const reconnectDelay = 3000 // 3秒重连间隔

  const connect = async () => {
    console.info(`[Stream] 尝试建立连接...`)

    try {
      const response = await fetch(url, {
        method: 'POST', // 使用 POST 请求
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify(data) // 数据通过请求体发送
      })
    console.info(`[Stream] 连接建立，状态：${response.status}`)
    console.info(response)
      if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`)
      }

      if (!response.body) {
        throw new Error('Response body is undefined')
      }

      const reader = response.body.getReader()
      const decoder = new TextDecoder()

      while (true) {
        const { done, value } = await reader.read()
        if (done) break

        const chunk = decoder.decode(value, { stream: true })
        console.info(`[Stream] 接收到消息：${chunk}`)

        try {
          const lines = chunk.split('\n\n').filter(line => line.startsWith('data: '))
          for (const line of lines) {
            const parsedData = JSON.parse(line.replace('data: ', ''))
            onMessage(parsedData)
          }
        } catch (e) {
          console.error('[Stream] 数据处理失败', e)
          onError(new Error('Stream数据处理失败'))
        }
      }
    } catch (error) {
      console.warn('[Stream] 连接出错', error)

      if (reconnectAttempts < maxReconnectAttempts) {
        reconnectAttempts++
        console.warn(`[Stream] 正在尝试第 ${reconnectAttempts} 次重连...`)
        setTimeout(connect, reconnectDelay)
      } else {
        console.error('[Stream] 重连失败，达到最大重连次数')
        onError(new Error('Stream连接重连失败'))
      }
    }
  }

  return connect()
}